<template>
    <div class="wrapper">
        <el-form ref="formRef" :model="formData">
            <el-form-item label="奖励方式" prop="reward_type" required>
                <el-radio-group
                    v-model="formData.reward_type"
                    :disabled="formDisabled || pageType == 'look'"
                    class="wrap-radio-group">
                    <el-radio :label="1">
                        <span>阶梯奖励</span>
                        <span class="form-tip"> 根据完成奖品任务的等级领取对应奖励，可以领取多个奖品 </span>
                    </el-radio>
                    <el-radio :label="2">
                        <span>单一奖励</span>
                        <span class="form-tip"> 完成多个奖品任务后，用户只可选择已完成中的一个奖品进行领取 </span>
                    </el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="" label-width="0" prop="reward_list">
                <div class="table-tip">
                    1）达到奖品任务条件后，奖品库存将被锁定；2）若助力失效，未领取/未核销的奖品库存会释放；3）单一奖励在领取某一个奖品之后，其他奖品库存将释放
                </div>
                <award-settings
                    ref="awardSettingsRef"
                    :period-type="props.basicDate.period_type"
                    :activity-time="props.basicDate.effect_date"
                    :form-disabled="formDisabled"
                    @submit="handleSubmitAward" />
            </el-form-item>
            <!-- <el-form-item label="奖品领完结束活动" prop="reward_end_switch" class="form-switch-item">
                <el-switch
                    v-model="formData.reward_end_switch"
                    :active-value="2"
                    :inactive-value="1"
                    :disabled="pageType == 'look'" />
                <span class="form-tip">开启后，在所有奖品领完之后活动将自动提前结束</span>
            </el-form-item> -->
        </el-form>
    </div>
</template>

<script setup lang="ts">
import bus from '@/utils/bus';
import { getBusinesspay } from '@/api/channelconfig/enterprisepayment';

import AwardSettings from '@/components/zw/activity/award-settings/index.vue';
import { reactive, ref, defineExpose, defineProps, withDefaults, watch, onMounted, inject, onBeforeMount } from 'vue';
import type { FormInstance } from 'element-plus';

interface Props {
    pageType: any;
    basicDate: any;
}
const props = withDefaults(defineProps<Props>(), {
    pageType: '',
    basicDate: () => ({})
});
const emit = defineEmits(['submit']);
const formRef = ref<FormInstance>();

/** 进行中、结束的情况下禁用 */
const formDisabled: any = inject('formDisabled');

const formData = ref<any>({
    reward_type: 1, //1阶梯奖励，2单一奖励
    reward_list: [
        {
            reward_type: 1, // 1: 实物， 2: 红包
            reward_title: '奖品一',
            reward_image: '//static.scrm.keyid.cn/assets/images/web-pc/default-liwu.png', // 是一段url
            reward_stock: 100, // int 类型
            help_num: 1, // int 类型
            // > 红包类型
            red_envelope_type: 1, // 1: 普通， 2: 拼手气
            red_envelope_money: 0.3, // float 类型,
            exchange_desc: '请确保获奖数据真实有效',
            // red_exchange_desc: undefined,
            // >> 拼手气红包
            red_envelope_total: 0, // float 类型
            red_envelope_range: 1, // 1: 高， 2: 中， 3: 低
            //}
            // 兑换设置
            exchange_usage_type: 1, // 1: 兑换码, 2: 线下邮寄，
            exchange_code_type: 1, // 1: 系统自动生成, 2: 导入兑奖码，
            exchange_file_list: [],
            exchange_time: [],
            // >> 线下邮寄 时才有， 否则是 []
            mail_info: [],
            is_update: 1 //是否更新客户信息  1-关 2-开
        }
    ],
    customer_type: 1, //类型限制
    help_effect: 1, // 助力有效性
    /** //奖品领完结束活动 1-否 2-是 */
    reward_end_switch: 1
});

const onSubmit = async () => {
    if (!formRef.value) return;
    const result = await formRef.value.validate();
    if (result) {
        emit('submit');
    }
};
watch(
    formData,
    (v: any) => {
        bus.emit('three', v.reward_list);
    },
    {
        deep: true
    }
);
const state = reactive({
    infoData: {
        merchant_sn: '',
        merchant_sn_disabled: false
    }
});
const onload = async () => {
    state.infoData = await getBusinesspay({});
    if (state.infoData.merchant_sn == '') {
        state.infoData.merchant_sn_disabled = true;
    }
};
const setFirstDefaultTime = () => {
    // 新增状态下，设置了开始和结束时间,动态添加所有的兑奖时间
    // if (props.pageType !== 'look' && props.pageType !== 'edit') {
    //     const time = defautlDate();
    //     for (const item of formData.value.reward_list) {
    //         if (!item.exchange_date?.length) {
    //             item.exchange_date = [...time];
    //         }
    //     }
    // }
};

onMounted(() => {
    onload();
});

const defautlDate = () => {
    // 活动期限的默认兑奖时间
    if (props.basicDate.period_type !== 2) return [];

    const eccStartDate = new Date(props.basicDate.effect_date[1]);
    const eccStartDate2 = new Date(props.basicDate.effect_date[0]);
    const endDate = new Date(eccStartDate.setDate(eccStartDate.getDate() + 30));
    const startDate = new Date(eccStartDate2);
    // const startDate = new Date(eccStartDate2.setSeconds(eccStartDate2.getSeconds() + 1))

    const padString = (time: number | string) => `${time}`.padStart(2, '0');
    const getDate = (datetime: any) => {
        const date = new Date(datetime);
        const year = date.getFullYear();
        const month = padString(date.getMonth() + 1);
        const day = padString(date.getDate());
        const HH = padString(date.getHours());
        const mm = padString(date.getMinutes());
        const ss = padString(date.getSeconds());
        return `${year}-${month}-${day} ${HH}:${mm}:${ss}`;
    };
    return [getDate(startDate), getDate(endDate)];
};

/* ----------------------------奖品列表-start---------------------------- */
const awardSettingsRef = ref();
/** 奖品列表设置默认值 */
const setDefaultAwardList = () => {
    awardSettingsRef.value?.setFormParams(formData.value);
};
onBeforeMount(setDefaultAwardList);

/** 新增/编辑/删除奖品同步更改列表 */
const handleSubmitAward = (data: any) => {
    formData.value.reward_list = data;
};
/* ----------------------------奖品列表-end---------------------------- */

defineExpose({
    onSubmit,
    formData,
    setFirstDefaultTime,
    setDefaultAwardList
});
</script>

<style lang="scss" scoped>
@mixin fz-m($fontSize: 16px) {
    font-family: PingFangSC-Medium, 'PingFang SC';
    font-size: $fontSize;
    font-weight: 500;
}

@mixin fz-r($fontSize: 14px) {
    font-family: PingFangSC-Regular, 'PingFang SC';
    font-size: $fontSize;
    font-weight: 400;
}

.table-tip {
    display: inline-block;
    margin-top: -16px;
    margin-bottom: 16px;
    padding: 6px 12px;
    color: #666;
    background-color: #fffaf9;
    line-height: 16px;

    @include fz-r(12px);
}

// 表单中右侧的提示
.form-tip {
    flex: 1;
    margin-left: 6px;
    color: #999;
    line-height: 18px;

    @include fz-r;
}

.wrap-radio-group {
    display: block;

    .el-radio {
        display: flex;
    }
}
</style>
